package com.yanqu.road.server.cmd.activity.ghost;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.pb.activity.GhostActivityProto;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.Command;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.ghost.GhostMgr;
import com.yanqu.road.server.manger.activity.ghost.GhostSceneLogic;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameProtocol;
import io.netty.channel.ChannelHandlerContext;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Cmd(code = GameProtocol.S_GHOST_SYNC_PLAYER_ACTION_FROM_CROSS, desc = "跨服同步鬼市玩家操作")
public class GhostSyncPlayerActionFromCrossCmd implements Command {

    @Override
    public void execute(ChannelHandlerContext ctx, YanQuMessage packet) throws Exception {

        ActivityInfo activityInfo = GhostMgr.getActivityInfo();
        if (!ActivityMgr.activityInTime(activityInfo)) {
            return;
        }

        GhostActivityProto.SyncGhostPlayerActionRespMsg reqMsg = GhostActivityProto.SyncGhostPlayerActionRespMsg.parseFrom(packet.getBytes());

        // 按bossId区分信息
        Map<Integer, GhostActivityProto.SyncGhostPlayerActionRespMsg.Builder> builderMap = new HashMap<>();
        for (GhostActivityProto.GhostPlayerActionMsg actionMsg : reqMsg.getActionListList()) {
            if (!builderMap.containsKey(actionMsg.getBossId())) {
                builderMap.put(actionMsg.getBossId(), GhostActivityProto.SyncGhostPlayerActionRespMsg.newBuilder());
            }
            GhostActivityProto.SyncGhostPlayerActionRespMsg.Builder tmpBuilder = builderMap.get(actionMsg.getBossId());
            tmpBuilder.addActionList(actionMsg);
        }

        for (Map.Entry<Integer, GhostActivityProto.SyncGhostPlayerActionRespMsg.Builder> builderEntry : builderMap.entrySet()) {
            int bossId = builderEntry.getKey();
            GhostActivityProto.SyncGhostPlayerActionRespMsg.Builder respMsg = builderEntry.getValue();
            // 发送给对应房间内的玩家
            List<Long> roomUserList = GhostSceneLogic.getRoomUserList(bossId);
            for (Long userId : roomUserList) {
                GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userId);
                if (onlinePlayer == null) {
                    // 下线了要退出房间
                    GhostSceneLogic.quitRoom(userId);
                } else {
                    onlinePlayer.sendPacket(ClientProtocol.U_GHOST_SYNC_PLAYER_ACTION, respMsg);
                }
            }
        }

    }
}
